package Server;

import java.sql.*;
import java.util.Random;

import static Server.MD5.md52;

public class UserDB {

    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/airconditionsystem" +
            "?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "admin";
    private Connection connection = null;
    private PreparedStatement pStmt = null;
    private ResultSet rs = null;

    public UserDB() {
        try {
            Class.forName(DRIVER);
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            if (connection != null) {
                connection.close();
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static String getToken(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sBuffer = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sBuffer.append(str.charAt(number));
        }
        return sBuffer.toString();
    }

    // 判断数据库中用户是否已存在
    public boolean userExist(String userId) throws SQLException {
        boolean exist = false;
        String sql = "SELECT * FROM user WHERE user_id=?";
        pStmt = connection.prepareStatement(sql);
        pStmt.setString(1, userId);
        rs = pStmt.executeQuery();
        if (rs.next()) {
            exist = true;
        }
        if (pStmt != null) {
            pStmt.close();
        }
        return exist;
    }

    // 超级管理员为经理和管理员注册账号
    public boolean create(String userId, String userPassword, String userAuth) {
        boolean state = false;
        try {
            if (!userExist(userId)) {
                String sql = "INSERT INTO user VALUES (?, ?, ?, ?)";
                String token = getToken(16);//随机生成
                pStmt = connection.prepareStatement(sql);
                pStmt.setString(1, userId);
                pStmt.setString(2, md52(userPassword));
                pStmt.setString(3, userAuth);
                pStmt.setString(4, token);
                pStmt.executeUpdate();
                state = true;
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (pStmt != null) {
                    pStmt.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return state;
    }

    public boolean rootLogin(String userId, String userPassword) {
        boolean state = false;
        try {
            String sql = "SELECT user_password, user_auth FROM user WHERE user_id=?";
            pStmt = connection.prepareStatement(sql);
            pStmt.setString(1, userId);
            rs = pStmt.executeQuery();
            if (rs.next()) {
                if (userPassword.equals(rs.getString("user_password"))
                        && rs.getInt("user_auth") == User.SUPERADMIN) {
                    //TODO:***********************************************
                    state = true;
                }
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (pStmt != null) {
                    pStmt.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return state;
    }

    public boolean userDelete(String userId) {
        boolean state = false;
        try {
            String sql = "DELETE FROM user WHERE user_id=?";
            pStmt = connection.prepareStatement(sql);
            pStmt.setString(1, userId);
            int cnt = pStmt.executeUpdate();
            if (cnt > 0) {
                state = true;
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (pStmt != null) {
                    pStmt.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return state;
    }
}
